package com.tl.wechat.mp.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tl.common.config.RuoYiConfig;
import com.tl.common.utils.DateUtils;
import com.tl.common.utils.file.FileUploadUtils;
import com.tl.common.utils.uuid.IdUtils;
import com.tl.wechat.config.WechatAccountConfig;
import com.tl.wechat.mp.domain.WechatTemplatOrderCancel;
import com.tl.wechat.mp.domain.WechatTemplatOrderSuccess;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

/**
 * 微信公众号处理
 * @author 15110
 *
 */
@Service
public class WechatMpService {
	
	private static final Logger log = LoggerFactory.getLogger(WechatMpService.class);

    @Autowired
    private WxMpService wxMpService;
    
    @Autowired
    private WechatAccountConfig accountConfig;
	
    
    /**
     * 发送订单成功模板消息
     */
    public void sendOrderSuccessTemplate(String templateId,String openId,WechatTemplatOrderSuccess wtos){
    	//实例化模板对象
    	WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
    	//设置模板ID
    	wxMpTemplateMessage.setTemplateId(templateId);
    	//设置发送给哪个用户
    	wxMpTemplateMessage.setToUser(openId);
    	//构建消息格式
    	List<WxMpTemplateData>list= Arrays.asList(
    		new WxMpTemplateData("first","测试"),
    		new WxMpTemplateData("character_string1",wtos.getOrderSn()),
    		new WxMpTemplateData("thing15",wtos.getGoodsName()),
    		new WxMpTemplateData("thing2",wtos.getServiceTypeName()),
    		new WxMpTemplateData("amount20",wtos.getPayPrice()),
    		new WxMpTemplateData("time6",wtos.getOrderTime()),
    		new WxMpTemplateData("remark","我发出来了")
    	);
    	//放进模板对象。准备发送
    	wxMpTemplateMessage.setData(list);
    	wxMpTemplateMessage.setUrl(accountConfig.getProjectUrl());
    	//发送模板
    	try {
			wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.info("模板信息发送失败：",e.getMessage());
		}
    }
    
    
    /**
     * 订单取消模板消息
     */
    public void sendOrderCancelTemplate(String templateId,String openId,WechatTemplatOrderCancel wtoc){
    	//实例化模板对象
    	WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
    	//设置模板ID
    	wxMpTemplateMessage.setTemplateId(templateId);
    	//设置发送给哪个用户
    	wxMpTemplateMessage.setToUser(openId);
    	//构建消息格式
    	List<WxMpTemplateData>list= Arrays.asList(
    		new WxMpTemplateData("character_string4",wtoc.getOrderSn()),
    		new WxMpTemplateData("thing2",wtoc.getGoodsName()),
    		new WxMpTemplateData("thing1",wtoc.getReason()),
    		new WxMpTemplateData("time6",wtoc.getCancelTime())
    	);
    	//放进模板对象。准备发送
    	wxMpTemplateMessage.setData(list);
    	wxMpTemplateMessage.setUrl(accountConfig.getProjectUrl());
    	//发送模板
    	try {
			wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.info("模板信息发送失败：",e.getMessage());
		}
    }
    
    
    
	/***
	 * 下载微信语音资源接口
	 * @param mediaId
	 * @return
	 * @throws WxErrorException 
	 */
	 public String downloadVoice(String mediaId) throws WxErrorException {
		 	InputStream inputStream = getWechatInputStream(mediaId);
			FileOutputStream fileOutputStream = null;  
	        int size=0;
		 try {
	        size = inputStream.available();
	        byte[] data = new byte[size];  
	        int len = 0;  
	        // 文件新路径
	        String filePath = getFilePath();
	        // 生成图片的绝对引用地址
	        fileOutputStream = new FileOutputStream(filePath);
	        while ((len = inputStream.read(data)) != -1) {  
                fileOutputStream.write(data, 0, len);  
                //String url=convertAmr2Mp3(propertieService.REPOSITORY_PATH+picUrl);
            }
		} catch (IOException e) {
			e.printStackTrace();
		}finally {  
            if (inputStream != null) {  
                try {  
                	inputStream.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (fileOutputStream != null) {  
                try {  
                	fileOutputStream.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            } 
		 }
		 return "";
	 }
	 
	 /**
	  * 远程下载文件流
	  * @param mediaId
	  * @return
	 * @throws WxErrorException 
	  */
	 public InputStream getWechatInputStream(String mediaId) throws WxErrorException {
		 	String accessToken=wxMpService.getAccessToken();
		 	InputStream is = null;  
	        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+accessToken+"&media_id="+mediaId;  
	        try {  
	        	URL realUrl = new URL(url);
	            URLConnection conn = realUrl.openConnection();
	            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            conn.connect();
	            is=conn.getInputStream();
	            System.out.println("文件流======："+is);
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        return is;
	 }
	 
	 
	/** 
     *  
     * 创建文件路径和文件名称
	 * @throws IOException 
     */  
	 private String getFilePath() throws IOException {
		 String fileName = DateUtils.datePath()+File.separator+IdUtils.fastSimpleUUID()+"."+"amr";
	     String path=FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(),fileName);
	     return path;
	 }
	 
}
